<?php
/**
* @version		$Id: default_modelfrontend.php 125 2012-10-09 11:09:48Z michel $
* @package		Cashbag
* @subpackage 	Models
* @copyright	Copyright (C) 2013, . All rights reserved.
* @license #
*/
 defined('_JEXEC') or die('Restricted access');


jimport('joomla.application.component.modelitem');
jimport('joomla.application.component.helper');

 require_once( JPATH_ADMINISTRATOR.DS. 'components'.DS.'com_virtuemart'.DS.'classes'.DS.'ps_user.php' );

JTable::addIncludePath(JPATH_ROOT.'/administrator/components/com_cashbag/tables');
/**
 * CashbagModelCashbag
 * @author $Author$
 */
 
 
class CashbagModelCashbag  extends JModelItem { 

	
	
	protected $context = 'com_cashbag.cashbag';   
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	1.6
	 */
        
        public function demanderSac(){
            
            $vmuser = & JFactory::getUser();
            $type   = JFactory::getApplication()->input->get('type');//le type de demande: sac ou etiquette
            $db     = & $this->getTable('cashbag');
            
            $record = new stdClass();
            
            $record->vm_user_id     = $vmuser->id;
             $record->ref_interne    = uniqid();
            $record->type_cashbag   = $type;
            $date                   = JFactory::getDate();
            
            $record->demandedOn     = $date->toFormat();
            $record->croix_rouge    = JFactory::getApplication()->input->get('croix_rouge');
            
            if(!$db->bind((array)$record))
                 JError::raiseError(500, $db->getError() );
            
            if(!$db->store())
                JError::raiseError(500, $db->getError() );
          
            //Récuperation des information de l'utilisateur
            
             /*if(!isset($result->title))
                return 'L\'utilisateur n\'existe pas';*/
            
            
           
            $array  = new stdClass();
            
            if($type == 'label'){
                
                $query  = $this->queryUserInfos();
            
                $db_2   = &JFactory::getDbo();

                $db_2->setQuery($query);

                $result = $db_2->loadObject();
                
                
                $result->ref_interne     = $record->ref_interne;
               // var_dump($result);die('m');
                return $result;
            }
            
            
        }
        
        function queryUserInfos(){
            
            $user  = &JFactory::getUser();
            
            $user_id    = $user->id;
            
            $query  ="SELECT virtuemart_userinfo_id AS user_info_id, title, last_name, first_name,
                                address_1, address_2, city, zip
                     FROM #__virtuemart_userinfos AS vu
                     WHERE vu.virtuemart_user_id = $user_id AND vu.address_type= 'BT' ";
            return $query;
            
        }
        
        function getAddrBag(){
            
            $db = &JFactory::getDbo();
            
            $query  = $this->queryUserInfos();
            
            $db->setQuery($query);
            
            $r  = $db->loadObject();
            
            //html form
            //titre
            $titre  = array();
            $titre[]        = JHTML::_('select.option', '','S&eacute;lectionnez');
            $titre[]        = JHTML::_('select.option', 'Mr', 'M');
            $titre[]        = JHTML::_('select.option', 'Mrs', 'Mme');
            $opt_titre      = JHTML::_('select.genericlist', $titre, 'titre', '', 'value', 'text', $r->title);
            
            
            $pren           = array();
            
            $form   = ' <table style="width:75%; margin-top:0;margin-left:12.5%;">
                        <tr> 
                            <td style="text-align:right;">
                                <label>Civilit&eacute;*</label>
                            </td>

                            <td style="text-align:left;">
                                '.$opt_titre.'
                            </td>
                    </tr>
                    <tr>
                    <td style="text-align:right;">
                        <label>Prenom *</label>
                    </td>
                    <td style="text-align:left;">
                         <input type="text" name="first_name" id="first_name" value="'.$r->first_name.'"/>
                    </td>
                </tr>
                <tr>
                    <td style="text-align:right;">
                        <label>Nom*</label>
                    </td>
                    <td style="text-align:left;">
                        <input type="text" name="last_name" id="last_name" value="'.$r->last_name.'"/>
                    </td>
                </tr>
                <tr>
                    <td style="text-align:right;">
                        <label> Adresse*</label>
                    </td>
                    <td style="text-align:left;">
                        <input type="text" name="address1" id="address1" value="'.$r->address_1.'" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align:right;">
                        <label>
                            Compl&eacute;ment
                        </label>
                    </td>
                    <td style="text-align:left;">
                        <input type="text" name="address2" id="address2" value="'.$r->address_2.'" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align:right;">
                        <label>Code postal*:</label>
                    </td>
                    <td style="text-align:left;">
                        <input type="text" id="zip" name="zip" value="'.$r->zip.'" />
                    </td>
                </tr>
                <tr>
                    <td style="text-align:right;">
                        <label>Ville*</label>
                    </td>
                    <td style="text-align:left;">
                        <input type="text" name="city" id="city" value="'.$r->city.'" />
                    </td>
                </tr>
                <tr>
                <td style="text-align:right;">
                Pays*
                </td>
                <td style="text-align:left;">
                <input type="text" name="country" id="country" value="France" disabled="true"/>
                <input type="hidden" name="userinfo_id" value="'.$r->user_info_id.'"/>
                </td>
                </tr>
                </table>
                ';
            
            return $form;
        }
        
        function saveNewAddr(){
            
            $app    = &JFactory::getApplication()->input;
           
            $record = new stdClass();
            $user  = &JFactory::getUser();
           
            //var_dump(htmlspecialchars($input));
            $record->virtuemart_user_id     = $user->id;
            $record->title                  = $app->get('titre');
            $record->first_name             = htmlspecialchars($_POST['first_name']);
            $record->last_name              = htmlspecialchars($_POST['last_name']);
            $record->address_1              = htmlspecialchars($_POST['address1']);
            $record->address_2              = htmlspecialchars($_POST['address2']);
            $record->zip                    = $app->get('zip');
            $record->city                   = $app->get('city');
            $record->address_type           = 'BT';
            $record->virtuemart_country_id  = 73;//Code de la France
            
            $record->virtuemart_userinfo_id = $app->get('userinfo_id');
            
            setcookie('zip', $record->zip, time()+3600);//enregistrement du zip dans les cookies!
            setcookie('city', $record->city, time()+3600);//enregistrement de la ville dans les cookies!
            setcookie('address', $record->address_1, time()+3600);
            
            if($record->virtuemart_userinfo_id == ''|| $record->virtuemart_userinfo_id==0){
                $res    = JFactory::getDbo()->insertObject('#__virtuemart_userinfos', $record);
            }else {
                $res    = JFactory::getDbo()->updateObject('#__virtuemart_userinfos', $record,'virtuemart_userinfo_id');
            }
           //var_dump($res);
            return $res;
        }
        
        function confirmer_cgu(){
            
            $app    = &JFactory::getApplication()->input;
            
            $croix_rouge    = $app->get('croix_rouge');
            
            setcookie('croix_rouge', $croix_rouge, time()+3600);//enregistrer la réponse sur la croix rouge ds les cookies
        }
        
        function sendMail_user(){
            $user = JFactory::getUser();
            
            $userInfo   = ps_user::getUserInfo( $user->id );
            
            $prenom     = $userInfo->last_name;
            $email      = $user->email;
        }
        function carte_kiala(){
            
            $carte  = array();
            
            $carte[]    = $_COOKIE['zip'];
            $carte[]    = $_COOKIE['city'];
            $ad         = $_COOKIE['address'];
            $carte[]    = str_replace(" ", '+', $ad);
            
            return $carte;
        }
        function modifier_publish(){
            
            $app    = &JFactory::getApplication();
            $pub    = $app->input->get('published');
            $id     = $app->input->get('id');
            
            $db     = &JFactory::getDbo();
            
            $query  = "UPDATE #__vm_cashbag SET published = $pub WHERE id = $id";
            
            $db->setQuery($query);
            
            return $db->query();
        }
        
        function displayInfo(){//retourne l'état des ventes d'un client
            
           $vmuser  = & JFactory::getUser();
           
           $id      = $vmuser->id;
           
           $db      = & JFactory::getDbo();
           
           $query   = "SELECT ref_interne,type_cashbag, demandedOn, sendOn, receivedOn, number_of_product_cash, cashbag_estimation, status
                        FROM #__vm_cashbag WHERE vm_user_id=".$id;
           
           $db->setQuery($query);
           
           return $db->loadObjectList();
        }
        
        function fnDecrypt($sValue, $sSecretKey)
        {
            return rtrim(
                mcrypt_decrypt(
                    MCRYPT_RIJNDAEL_256, 
                    $sSecretKey, 
                    base64_decode($sValue), 
                    MCRYPT_MODE_ECB,
                    mcrypt_create_iv(
                        mcrypt_get_iv_size(
                            MCRYPT_RIJNDAEL_256,
                            MCRYPT_MODE_ECB
                        ), 
                        MCRYPT_RAND
                    )
                ), "\0"
            );
        }
        
         function check_locked(){//verifie si un accord est toujours valide
            
            $app = &JFactory::getApplication();
            
            $ref_inter  = $app->input->get('key');
            
            
            if($ref_inter =='')
                return ;//l'url n'est pas valide
            
            /*$ref_inter  = $this->fnDecrypt($ref_crypt, 'abadingo');
            
            echo $ref_crypt;*/
           
            
            $db = &JFactory::getDbo();
            
            $query  = "SELECT id, date_locked "
                    . " FROM #__vm_cashbag"
                    . " WHERE ref_interne = '$ref_inter' AND published=2";
            
            $db->setQuery($query);
            //var_dump($query);
            $r = $db->loadObject();
            return $r;//retourne soit -1 = KO soit 0 = OK
        }
        
	public function populateState()
	{
		$app = JFactory::getApplication();

		//$params	= $app->getParams();

		// Load the object state.
		$id	= JRequest::getInt('id');
		$this->setState('cashbag.id', $id);

		// Load the parameters.
		//TODO: componenthelper
		//$this->setState('params', $params);
	}

	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':'.$this->getState('cashbag.id');

		return parent::getStoreId($id);
	}
	
	/**
	 * Method to get an ojbect.
	 *
	 * @param	integer	The id of the object to get.
	 *
	 * @return	mixed	Object on success, false on failure.
	 */
	public function &getItem($id = null)
	{
		if ($this->_item === null) {
			
			$this->_item = false;

			if (empty($id)) {
				$id = $this->getState('cashbag.id');
			}

			// Get a level row instance.
			$table = JTable::getInstance('Cashbag', 'Table');


			// Attempt to load the row.
			if ($table->load($id)) {
				
				// Check published state.
				if ($published = $this->getState('filter.published')) {
					
					if ($table->state != $published) {
						return $this->_item;
					}
				}

				// Convert the JTable to a clean JObject.
				$this->_item = JArrayHelper::toObject($table->getProperties(1), 'JObject');
				
			} else if ($error = $table->getError()) {
				
				$this->setError($error);
			}
		}


		return $this->_item;
	}
		
}
?>